using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using Wikey.Domain.Components;
using Wikey.Entity;

namespace Wikey.Domain.Repository
{
    public interface ITagRepository
    {
        int Save(string name);
        Tag Find(int id);
        Tag Find(string name);
        List<Tag> SelectAll();
        IList<Tag> FindTagsOf(string[] strings);
    }

    public class TagRepository : Repository, ITagRepository
    {
        public TagRepository(ISessionSource source) : base(source)
        {
        }

        public TagRepository(ISession session) : base(session)
        {
        }

        public int Save(string name)
        {
            var tag = Find(name);
            if( tag == null )
            {
                tag = new Tag() {Id = 0, Name = name};
            }
            else
            {
                return tag.Id;
            }

            base.Save(tag);
            return tag.Id;
        }

        public Tag Find(int id)
        {
            return base.Find<Tag>(id);   
        }

        public Tag Find(string name)
        {
            var q = from t in Context().Tags where t.Name.Equals(name) select t;
            return q.FirstOrDefault();
        }

        public List<Tag> SelectAll()
        {
            return (from t in Context().Tags select t).ToList();
        }

        public IList<Tag> FindTagsOf(string[] strings)
        {
            return (from t in Context().Tags where strings.Contains(t.Name) orderby t.Name select t).ToList();
        }

        private static bool WithinTags( Tag t , IEnumerable<string> items)
        {
            foreach (var str in items) {
                if (t.Name.Contains(str)) {
                    return true;
                }
            }
            return false;
        }
    }
}